package com.liukaixin.product.ru.business.competition.competitionlist;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Toast;

import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;
import com.liukaixin.product.ru.Injection;
import com.liukaixin.product.ru.LazyLoadFragment;
import com.liukaixin.product.ru.R;
import com.liukaixin.product.ru.business.competition.competitiondesc.CompetitionDescActivity;
import com.liukaixin.product.ru.data.model.Competition;
import com.liukaixin.product.ru.enumerate.CompetitionTypeEnum;
import com.orhanobut.logger.Logger;

import java.util.List;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * 竞赛列表fragment.
 * <p>
 * 流程:
 * 一进入执行onRefresh方法
 * 下拉时执行loadMore方法
 * 上拉时执行onRefresh方法.
 * <p>
 * Created by liukaixin on 16/8/29.
 */
public class CompetitionsFragment extends LazyLoadFragment
        implements CompetitionsContract.View,
        RecyclerArrayAdapter.OnLoadMoreListener, SwipeRefreshLayout.OnRefreshListener,
        View.OnClickListener {

    private CompetitionsContract.Presenter presenter;

    private CompetitionsAdapter competitionsAdapter;

    private Integer page = 1;

    private Boolean isFabOpen = false;

    private FloatingActionButton typeFab;
    private FloatingActionButton elseFab;
    private FloatingActionButton itScienceFab;
    private FloatingActionButton artFab;
    private FloatingActionButton startupsFab;
    private FloatingActionButton projectFab;
    private FloatingActionButton allFab;

    private Animation rotateBackward;
    private Animation rotateForward;
    private Animation fabOpen;
    private Animation fabClose;

    private EasyRecyclerView recyclerView;

    private final static String CURRENT_COMPETITION_TYPE = "CURRENT_COMPETITION_TYPE";

    public CompetitionsFragment() {
        // Requires empty public constructor
    }

    public static CompetitionsFragment newInstance() {
        return new CompetitionsFragment();
    }

    @Override
    public void setPresenter(@NonNull CompetitionsContract.Presenter presenter) {
        this.presenter = checkNotNull(presenter);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        competitionsAdapter = new CompetitionsAdapter(getActivity());
        // Create the presenter
        presenter = new CompetitionsPresenter(Injection
                .provideCompetitionsRepository(), this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {

        return inflater.inflate(R.layout.fragment_competitions, container, false);
    }

    @Override
    public void initData() {
        presenter.getData(1);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // Set up the competitions view
        recyclerView = (EasyRecyclerView) view.findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setAdapterWithProgress(competitionsAdapter);
        recyclerView.setRefreshListener(this);
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        competitionsAdapter.setMore(R.layout.view_more, this);
        competitionsAdapter.setNoMore(R.layout.view_no_more);
        competitionsAdapter.setOnItemClickListener(
                this::toCompetitionActivity);
        competitionsAdapter.setError(R.layout.view_error)
                .setOnClickListener(
                        v -> competitionsAdapter.resumeMore());

        // Set up the floating action buttons
        typeFab = (FloatingActionButton) view.findViewById(R.id.type_fab);
        typeFab.setOnClickListener(this);
        elseFab = (FloatingActionButton) view.findViewById(R.id.else_fab);
        elseFab.setOnClickListener(this);
        artFab = (FloatingActionButton) view.findViewById(R.id.art_fab);
        artFab.setOnClickListener(this);
        itScienceFab = (FloatingActionButton) view.findViewById(R.id.it_science_fab);
        itScienceFab.setOnClickListener(this);
        startupsFab = (FloatingActionButton) view.findViewById(R.id.startups_fab);
        startupsFab.setOnClickListener(this);
        projectFab = (FloatingActionButton) view.findViewById(R.id.project_fab);
        projectFab.setOnClickListener(this);
        allFab = (FloatingActionButton) view.findViewById(R.id.all_fab);
        allFab.setOnClickListener(this);

        // Set up the animations
        rotateBackward = AnimationUtils.loadAnimation(getActivity().getApplicationContext()
                , R.anim.rotate_backward);
        rotateForward = AnimationUtils.loadAnimation(getActivity().getApplicationContext()
                , R.anim.rotate_forward);
        fabOpen = AnimationUtils.loadAnimation(getActivity().getApplicationContext()
                , R.anim.list_fab_open);
        fabClose = AnimationUtils.loadAnimation(getActivity().getApplicationContext()
                , R.anim.list_fab_close);

        // Load previously saved state, if available.
        if (savedInstanceState != null) {
            CompetitionTypeEnum competitionTypeEnum =
                    (CompetitionTypeEnum) savedInstanceState.
                            getSerializable(CURRENT_COMPETITION_TYPE);
            presenter.setFiltering(competitionTypeEnum);
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putSerializable(CURRENT_COMPETITION_TYPE,
                presenter.getFiltering());

        super.onSaveInstanceState(outState);
    }

    private void toCompetitionActivity(Integer position) {
        Intent toCompetition = new Intent(getContext(), CompetitionDescActivity.class);
        toCompetition.putExtra(CompetitionDescActivity.EXTRA_COMPETITION_ID,
                competitionsAdapter.getItem(position).getId());
        toCompetition.putExtra(CompetitionDescActivity.EXTRA_PIC_URL,
                competitionsAdapter.getItem(position).getPic());
        toCompetition.putExtra(CompetitionDescActivity.EXTRA_COMPETITION_NAME,
                competitionsAdapter.getItem(position).getName());
        startActivity(toCompetition);
    }

    @Override
    public void onRefresh() {
        Logger.d("刷新竞赛列表");
        presenter.refresh();
    }

    @Override
    public void onLoadMore() {
        page++;
        Logger.d("加载第%d页竞赛数据", page);
        presenter.loadMore(page);
    }

    @Override
    public void showError(String msg) {
        Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showData(List<Competition> competitions) {
        competitionsAdapter.addAll(competitions);
    }

    @Override
    public void showNoData() {
        recyclerView.showEmpty();
    }

    @Override
    public void clearAdapter() {
        competitionsAdapter.clear();
    }

    @Override
    public void initPage() {
        page = 1;
    }

    @Override
    public void setNoMoreData() {
        competitionsAdapter.stopMore();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.type_fab:
                fabClicked();
                break;
            case R.id.all_fab:
                Logger.d("ALL_FAB CLICKED");
                fabClicked();
                presenter.setFiltering(CompetitionTypeEnum.ALL);
                onRefresh();
                break;
            case R.id.else_fab:
                Logger.d("ELSE_FAB CLICKED");
                fabClicked();
                presenter.setFiltering(CompetitionTypeEnum.ELSE);
                onRefresh();
                break;
            case R.id.art_fab:
                Logger.d("ART_FAB CLICKED");
                fabClicked();
                presenter.setFiltering(CompetitionTypeEnum.ART);
                onRefresh();
                break;
            case R.id.it_science_fab:
                Logger.d("IT_FAB CLICKED");
                fabClicked();
                presenter.setFiltering(CompetitionTypeEnum.IT_SCIENCE);
                onRefresh();
                break;
            case R.id.startups_fab:
                Logger.d("STARTUPS_FAB CLICKED");
                fabClicked();
                presenter.setFiltering(CompetitionTypeEnum.STARTUPS);
                onRefresh();
                break;
            case R.id.project_fab:
                Logger.d("PROJECT_FAB CLICKED");
                fabClicked();
                presenter.setFiltering(CompetitionTypeEnum.PROJECT);
                onRefresh();
                break;
            default:
                break;
        }
    }

    private void fabClicked() {
        if (isFabOpen) {
            typeFab.startAnimation(rotateBackward);
            allFab.startAnimation(fabClose);
            allFab.setClickable(false);
            elseFab.startAnimation(fabClose);
            elseFab.setClickable(false);
            artFab.startAnimation(fabClose);
            artFab.setClickable(false);
            itScienceFab.startAnimation(fabClose);
            itScienceFab.setClickable(false);
            startupsFab.startAnimation(fabClose);
            startupsFab.setClickable(false);
            projectFab.startAnimation(fabClose);
            projectFab.setClickable(false);
            isFabOpen = false;
        } else {
            typeFab.startAnimation(rotateForward);
            allFab.startAnimation(fabOpen);
            allFab.setClickable(true);
            elseFab.startAnimation(fabOpen);
            elseFab.setClickable(true);
            artFab.startAnimation(fabOpen);
            artFab.setClickable(true);
            itScienceFab.startAnimation(fabOpen);
            itScienceFab.setClickable(true);
            startupsFab.startAnimation(fabOpen);
            startupsFab.setClickable(true);
            projectFab.startAnimation(fabOpen);
            projectFab.setClickable(true);
            isFabOpen = true;
        }
    }
}
